package com.rocksdata.mc.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ctz.commonframe.ui.BaseFragment;
import com.ctz.commonframe.ui.widget.AbsAdapter;
import com.ctz.commonframe.ui.widget.AdapterViewHolder;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.entity.TeacherInfo;
import com.rocksdata.mc.ui.activity.ContactActivity;
import com.rocksdata.mc.ui.activity.TeacherDetailActivity;
import com.rocksdata.mc.Constant;
import com.rocksdata.mc.R;
import com.rocksdata.mc.entity.TeacherContactInfo;
import com.rocksdata.mc.entity.UserInfo;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by 陈堂正 on 2017/3/18.
 */
@ContentView(R.layout.fragment_contact_list)
public class TeacherContactListFragment extends BaseFragment implements TextWatcher{
    @ViewInject(R.id.lv_contact)
    private ExpandableListView lvContact;
    @ViewInject(R.id.etSearch)
    private EditText etSearch;
    @ViewInject(R.id.lv_search)
    private ListView searchListView;
    @ViewInject(R.id.layout_search)
    private LinearLayout layoutSearch;
    @ViewInject(R.id.layout_all_select)
    private RelativeLayout layoutAllSelect;
    @ViewInject(R.id.cb_all_select)
    private CheckBox cbAllSelect;
    @ViewInject(R.id.tv_selected_count)
    private TextView tvSelectedCount;

    private int contactType;
    private TeacherContactAdapter adapter;
    private ContactsSearchAdapter searchAdapter;

    private List<TeacherContactInfo> selectedList;
    private List<String> selectedUserList;
    //所有联系人数据
    private List<TeacherContactInfo> contactList = new ArrayList<TeacherContactInfo>();
    private int allUserCount;
    //查询后的联系人数据
    private List<TeacherContactInfo> searchContactList = new ArrayList<TeacherContactInfo>();

    private List<TeacherInfo> tempRemoveList = new ArrayList<TeacherInfo>();
    private boolean isMultiselectMode;
    private boolean isAllSelect;
    private boolean isChatMode;

    private ContactActivity.OnSearchResultListener onSearchResultListener = new ContactActivity.OnSearchResultListener() {
        @Override
        public void onSearchResult(CharSequence charSequence) {
            if (TextUtils.isEmpty(charSequence)) {
                lvContact.setVisibility(View.VISIBLE);
                searchListView.setVisibility(View.GONE);
                adapter.notifyDataSetChanged();
            } else {
                lvContact.setVisibility(View.GONE);
                searchListView.setVisibility(View.VISIBLE);
                List<TeacherInfo> tempSearchList = new ArrayList<TeacherInfo>();
                for (TeacherContactInfo info : contactList) {
                    for (TeacherInfo user : info.getStaffs()) {
                        if (user.getStaffName().startsWith(charSequence.toString().trim())) {
                            tempSearchList.add(user);
                        }
                    }
                }
                searchAdapter = new ContactsSearchAdapter(mContext, tempSearchList, isMultiselectMode);
                searchListView.setAdapter(searchAdapter);
            }
        }
    };

    public boolean isAllSelected(){
        if(isMultiselectMode){
            return cbAllSelect.isChecked();
        }
        return false;
    }

    public ArrayList<String> getSelectedStaffNums(){
        if(isMultiselectMode){
            ArrayList<String> list = new ArrayList<String>();
            for(TeacherContactInfo info : contactList){
                for(TeacherInfo user : info.getStaffs()){
                    if(user.isChecked()){
                        list.add(user.getStaffCode());
                    }
                }
            }
            return list;
        }
        return null;
    }

    public List<TeacherContactInfo> getSelectedList(){
        if(isMultiselectMode) {
            List<TeacherContactInfo> list = new ArrayList<TeacherContactInfo>();
            for (TeacherContactInfo info : contactList) {
                if(info.isChecked){
                    list.add(info);
                }else{
                    List<TeacherInfo> userlist = new ArrayList<TeacherInfo>();
                    for (TeacherInfo user : info.getStaffs()) {
                        if (user.isChecked()) {
                            userlist.add(user);
                        }
                    }
                    if(userlist.size() > 0){
                        info.setStaffs(userlist);
                        list.add(info);
                    }
                }
            }
            return list;
        }
        return null;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        contactType = bundle.getInt(Constant.EXTRA_KEY_CONTACT_TYPE);
        isChatMode = bundle.getBoolean(Constant.EXTRA_KEY_CHAT_MODE);
        isMultiselectMode = bundle.getBoolean(Constant.EXTRA_KEY_MULTISELECT_MODE);
        selectedList = (List<TeacherContactInfo>) bundle.getSerializable(Constant.EXTRA_KEY_NOTIFICATION_TARGET_SELECTED);
        selectedUserList = bundle.getStringArrayList(Constant.EXTRA_KEY_MULTISELECT_USER_LIST);
        initView();
        super.onViewCreated(view, savedInstanceState);
        getContactList();
    }

//    @Override
//    protected void onVisible() {
//        getContactList();
//    }

    private void initView() {
        layoutSearch.setVisibility(View.GONE);
//        layoutSearch.setVisibility(isMultiselectMode ? View.GONE: View.VISIBLE);
        layoutAllSelect.setVisibility(isMultiselectMode ? View.VISIBLE : View.GONE);
        cbAllSelect.setChecked(false);
        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence str, int arg1, int arg2, int arg3) {

                if (TextUtils.isEmpty(str)) {
                    lvContact.setVisibility(View.VISIBLE);
                    searchListView.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                } else {
                    lvContact.setVisibility(View.GONE);
                    searchListView.setVisibility(View.VISIBLE);
                    List<TeacherInfo> tempSearchList = new ArrayList<TeacherInfo>();
                    for (TeacherContactInfo info : contactList) {
                        for (TeacherInfo user : info.getStaffs()) {
                            if (user.getStaffName().startsWith(str.toString().trim())) {
                                tempSearchList.add(user);
                            }
                        }
                    }
                    searchAdapter = new ContactsSearchAdapter(mContext, tempSearchList, isMultiselectMode);
                    searchListView.setAdapter(searchAdapter);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        if(mContext instanceof ContactActivity){
            ((ContactActivity)mContext).setOnSearchResultListener(onSearchResultListener);
        }
//        else if (mContext instanceof ChatContactListActivity){
//            ((ChatContactListActivity)mContext).setOnSearchResultListener(onSearchResultListener);
//        }

        adapter = new TeacherContactAdapter(getActivity(), contactList, isMultiselectMode);
        lvContact.setAdapter(adapter);
    }

    @Event(value = {R.id.cb_all_select})
    private void onClick(View view) {
        switch (view.getId()){
            case R.id.cb_all_select:
                isAllSelect = !isAllSelect;
                cbAllSelect.setChecked(isAllSelect);
                for(TeacherContactInfo info: contactList){
                    info.isChecked = isAllSelect;
                    for(UserInfo user: info.getStaffs()){
                        user.setChecked(isAllSelect);
                    }
                }
                adapter.notifyDataSetChanged();
                tvSelectedCount.setText("已选" + (isAllSelect ? allUserCount : 0) + "人");
                break;
        }
    }

    @Event(value = {R.id.lv_search}, type = AdapterView.OnItemClickListener.class)
    private void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        if(!isMultiselectMode) {
            TeacherInfo userInfo = searchAdapter.getItem(arg2);
            if(isChatMode){
                gotoChatActivity(userInfo);
            }else {
                gotoDetailActivity(userInfo);
            }
        }
    }

    @Event(value = {R.id.lv_contact}, type = ExpandableListView.OnChildClickListener.class)
    private boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        if(!isMultiselectMode) {
            TeacherInfo userInfo = adapter.getChild(groupPosition, childPosition);
            if(isChatMode){
                gotoChatActivity(userInfo);
            }else {
                gotoDetailActivity(userInfo);
            }
        }
        return true;
    }

    private void gotoDetailActivity(TeacherInfo userInfo){
        Intent intent = new Intent(mContext, TeacherDetailActivity.class);
        intent.putExtra(Constant.KEY_USER_ID, userInfo.getStaffCode());
        startActivity(intent);
    }

    private void gotoChatActivity(TeacherInfo userInfo){
//        if(!userInfo.getStaffCode().equals(UserInfoManager.getCurrentUserId()))
//            RongIM.getInstance().startPrivateChat(mContext, userInfo.getStaffCode(), userInfo.getStaffName());
//        Intent intent = new Intent(mContext, ChatActivity.class);
//        intent.putExtra(Constant.KEY_USER_ID, userInfo.getStaffCode());
//        startActivity(intent);
    }

    private void getContactList() {
        if(contactList.size() == 0) {
            List<TeacherContactInfo> list = BusinessManager.getUserInfoManager().getTeacherList();
            if(list != null) {
                contactList.addAll(list);
                if (selectedUserList != null && selectedUserList.size() > 0) {
                    for (TeacherContactInfo info : contactList) {
                        for (TeacherInfo teacher : info.getStaffs()) {
                            if (selectedUserList.contains(teacher.getStaffCode())) {
                                info.getStaffs().remove(teacher);
                            }
                        }
                    }
                }
                for (TeacherContactInfo info : contactList) {
                    allUserCount += info.getStaffs().size();
                }
                if (selectedList != null && selectedList.size() > 0) {

                    for (TeacherContactInfo selectedInfo : selectedList) {
                        for (TeacherContactInfo info : contactList) {
                            if (info.getDepartmentCode().equals(selectedInfo.getDepartmentCode())) {
                                info.isChecked = selectedInfo.isChecked;
                                for (TeacherInfo selectedUser : selectedInfo.getStaffs()) {
                                    for (TeacherInfo user : info.getStaffs()) {
                                        if (selectedUser.getStaffCode().equals(user.getStaffCode())) {
                                            user.setChecked(selectedUser.isChecked());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                checkIsAllSelected();
            }
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length() > 0) {
            layoutAllSelect.setVisibility(View.GONE);
            searchContactList.clear();
            tempRemoveList.clear();
            for (TeacherContactInfo info: contactList) {
                if(info.getDepartmentName().contains(s)){
                    searchContactList.add(info);
                }else{
                    for(TeacherInfo user: info.getStaffs()){
                        if(!user.getStaffName().contains(s)){
                            info.getStaffs().remove(user);
                            tempRemoveList.add(user);
                        }
                    }
                    if(info.getStaffs().size() > 0){
                        searchContactList.add(info);
                    }
                }
            }
            adapter = new TeacherContactAdapter(mContext, searchContactList, isMultiselectMode);
        }else{
            layoutAllSelect.setVisibility(View.VISIBLE);
            for(TeacherContactInfo info: contactList){
                for(TeacherInfo user: tempRemoveList){
                    if(info.getDepartmentCode().equals(user.getDepartment().getDepartmentCode())){
                        info.getStaffs().add(user);
                    }
                }
            }
            for(TeacherContactInfo info: contactList){
                int checkedCount = 0;
                for(TeacherInfo user: info.getStaffs()){
                    if(user.isChecked()){
                        checkedCount++;
                    }
                }
                info.isChecked = checkedCount == info.getStaffs().size();
            }
            checkIsAllSelected();
            adapter = new TeacherContactAdapter(mContext, contactList, isMultiselectMode);
        }
        lvContact.setAdapter(adapter);
    }

    private void checkIsAllSelected(){
        int selectedCount = 0;
        for(TeacherContactInfo info: contactList){
            for(TeacherInfo user: info.getStaffs()){
                if(user.isChecked()){
                    selectedCount++;
                }
            }
        }
        cbAllSelect.setChecked(allUserCount == selectedCount);
        tvSelectedCount.setText("已选" + selectedCount + "人");
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private class TeacherContactAdapter extends BaseExpandableListAdapter {
        private Context context;
        private List<TeacherContactInfo> contactList;
        private boolean isMultiselectMode;

        public TeacherContactAdapter(Context context, List<TeacherContactInfo> contactList, boolean isMultiselectMode) {
            this.context = context;
            this.contactList = contactList;
            this.isMultiselectMode = isMultiselectMode;
        }

        @Override
        public int getGroupCount() {
            return contactList.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            List<TeacherInfo> userList = contactList.get(groupPosition).getStaffs();
            int count = 0;
            if (userList != null) {
                count = userList.size();
            }
            return count;
        }

        @Override
        public TeacherContactInfo getGroup(int groupPosition) {
            return contactList.get(groupPosition);
        }

        @Override
        public TeacherInfo getChild(int groupPosition, int childPosition) {
            return contactList.get(groupPosition).getStaffs().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            final TeacherContactInfo contactInfo = getGroup(groupPosition);
            final GroupViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_contact_list_group, null);
                holder = new GroupViewHolder();
                holder.ivFlag = (ImageView) convertView.findViewById(R.id.iv_expanded_flag);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tvCount = (TextView) convertView.findViewById(R.id.tv_count);
                holder.cbGroup = (CheckBox) convertView.findViewById(R.id.cb_contact_group);
                convertView.setTag(holder);
            } else {
                holder = (GroupViewHolder) convertView.getTag();
            }
            //设置多选框状态
            if(isMultiselectMode){
                holder.cbGroup.setVisibility(View.VISIBLE);
                holder.cbGroup.setFocusable(false);
                holder.cbGroup.setChecked(contactInfo.isChecked);
                holder.cbGroup.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        contactInfo.isChecked = !contactInfo.isChecked;
                        for(UserInfo user: contactInfo.getStaffs()){
                            user.setChecked(contactInfo.isChecked);
                        }
                        notifyDataSetChanged();
                        checkIsAllSelected();
                    }
                });
                int count = 0;
                for(TeacherInfo t: contactInfo.getStaffs()){
                    if(t.isChecked())
                        count++;
                }
                holder.tvCount.setText(count + "/" + getChildrenCount(groupPosition) + "人");
            }else{
                holder.cbGroup.setVisibility(View.GONE);
                holder.tvCount.setText(getChildrenCount(groupPosition) + "人");
            }
            // 设置箭头状态
            if (isExpanded) {
                holder.ivFlag.setImageResource(R.mipmap.ic_indicator_expanded);
            } else {
                holder.ivFlag.setImageResource(R.mipmap.ic_indicator_unexpanded);
            }
            holder.tvName.setText(getGroup(groupPosition).getDepartmentName());
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView,
                                 ViewGroup parent) {
            final UserInfo userInfo = getChild(groupPosition, childPosition);
            ChildViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_contact_list_child, null);
                holder = new ChildViewHolder();
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                holder.cbChild = (CheckBox) convertView.findViewById(R.id.cb_contact_child);
                convertView.setTag(holder);
            } else {
                holder = (ChildViewHolder) convertView.getTag();
            }

            if(isMultiselectMode){
                holder.cbChild.setVisibility(View.VISIBLE);
                holder.cbChild.setFocusable(false);
                holder.cbChild.setChecked(userInfo.isChecked());
                holder.cbChild.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        userInfo.setChecked(!userInfo.isChecked());
                        TeacherContactInfo contactInfo = getGroup(groupPosition);
                        if(userInfo.isChecked()) {
                            boolean isAllChildChecked = true;
                            for (TeacherInfo user: contactInfo.getStaffs()) {
                                if(!user.isChecked()){
                                    isAllChildChecked = false;
                                    break;
                                }
                            }
                            contactInfo.isChecked = isAllChildChecked;
                        }else{
                            contactInfo.isChecked = false;
                        }
                        notifyDataSetChanged();
                        checkIsAllSelected();
                    }
                });
            }else{
                holder.cbChild.setVisibility(View.GONE);
            }

            holder.tvName.setText(getChild(groupPosition, childPosition).getStaffName());
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        class GroupViewHolder {
            ImageView ivFlag;
            TextView tvName;
            TextView tvCount;
            CheckBox cbGroup;
        }

        class ChildViewHolder {
            TextView tvName;
            CheckBox cbChild;
        }
    }

    private class ContactsSearchAdapter extends AbsAdapter<TeacherInfo> {
        private boolean isMultiselectMode;
        public ContactsSearchAdapter(Context context, List<TeacherInfo> datas, boolean isMultiselectMode) {
            super(context, datas, R.layout.item_contact_list_child);
            this.isMultiselectMode = isMultiselectMode;
        }

        @Override
        public void convert(AdapterViewHolder holder, final TeacherInfo data) {
            TextView tvName = holder.getView(R.id.tv_name);
            tvName.setText(data.getStaffName());
            CheckBox cbUser = holder.getView(R.id.cb_contact_child);
            if(isMultiselectMode){
                cbUser.setVisibility(View.VISIBLE);
                cbUser.setChecked(data.isChecked());
                cbUser.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        data.setChecked(!data.isChecked());
                        TeacherContactInfo parent = null;
                        for(TeacherContactInfo info: contactList){
                            if(info.getDepartmentCode().equals(data.getDepartment().getDepartmentCode())){
                                parent = info;
                                break;
                            }
                        }
                        if(data.isChecked()) {
                            boolean isAllChildChecked = true;
                            for (TeacherInfo user: parent.getStaffs()) {
                                if(!user.isChecked()){
                                    isAllChildChecked = false;
                                    break;
                                }
                            }
                            parent.isChecked = isAllChildChecked;
                        }else{
                            parent.isChecked = false;
                        }
                        notifyDataSetChanged();
                    }
                });
            }else{
                cbUser.setVisibility(View.GONE);
            }
        }
    }

}
